/**
 * 功能： 截去字符串左右的空格
 * 输入： 欲处理字符串
 * 输出： 处理后字符串
 * 补充过滤中文空格
 */
String.prototype.trim = function(){
    return this.replace(/(^(\s|\u3000)*)|((\s|\u3000)*$)/g, '');
};

var Utils = function(){
    function isUndefined(variable) {
        return typeof variable == 'undefined' ? true : false;
    }
    
    /** 计算字符串长度，考虑中英文 */
    function getLength(value) {
        return value.replace(/[^\x00-\xff]/g,"**").length;
    }
    /** 判断是否是emoji */
    function isEmojiCharacter(codePoint) {
        return !((codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }
	return {
		/**计算元素在数组的位置 返回下标,不存在对应元素则返回-1*/
		arrIndexOf : function(arr, a) {
			if(!arr || arr.length == 0 || !a)
				return -1;
			for(var i=0; i<arr.length; i++) {
				if(a == arr[i])
					return i;
			}	
			return -1;
		},
		/**数组中删除某一元素*/
		arrRemove : function(arr, a) {
			var i = Utils.arrIndexOf(arr, a); 
			if(i <= -1)
				return;
			arr.splice(i, 1);
		},
		/**移动数组中元素的位置*/
		arrMove : function(arr, index, moveType) {
			if(!arr || arr.length == 0 || index < 0 || index > arr.length || "up,down".indexOf(moveType) < 0)
				return;
			if(("up" == moveType && index == 0) || ("down" == moveType && index == arr.length-1))
				return;				
			var descIdx = 'up' == moveType ? index - 1 : index + 1;
			var temp = arr[descIdx];
			arr[descIdx] = arr[index];
			arr[index] = temp; 
			return;
		},
		//按长度截取字符串 超过长度用...替换
		substr : function(str, len){
			if (!str || str.length <= len) 
				return str;
			else
				return str.substring(0, len) + '...';
		},
		/**
		 * 将dateline转换成字符串
		 * 并以yyyy-MM-dd HH:mm形式返回
		 */
		formatDatelineToStr : function(dateline){
			if(!Number(dateline)) 
				return dateline;
			if(!dateline) return '';
			dateline = dateline*1000;
			var d = new Date();
			d.setTime(dateline);
			return d.getFullYear()
						+"-"+(d.getMonth()<9 ? '0':'')+(d.getMonth()+1)
						+"-"+(d.getDate()<10 ? '0':'')+d.getDate()
						+" "+(d.getHours()<10 ? '0':'')+d.getHours()
						+":"+(d.getMinutes()<10 ? '0':'')+d.getMinutes();
		},
		getCurrTimeSeconds : function() {
			return new Date().getTime() / 1000;
		},
		getCurrTimeStr : function(){
			var d = new Date();
			return d.getFullYear()
						+(d.getMonth()<9 ? '0':'')+(d.getMonth()+1)
						+(d.getDate()<10 ? '0':'')+d.getDate()
						+(d.getHours()<10 ? '0':'')+d.getHours()
						+(d.getMinutes()<10 ? '0':'')+d.getMinutes()
						+(d.getSeconds()<10 ? '0':'')+d.getSeconds();
		},		
		/**
		 * 将yyyy-MM-dd HH:mm形式字符串转换成dateline返回
		 */
		formatStrToDateline : function(str){
			if(!str) return null;
			str = str.replace(/-/g,'/');//替换全部- 为 /
			var d = Date.parse(str);
			if(d)
				return d/1000;
			return null;
		},
		/**
		 * 将dateline转换成字符串，以距今的时间形式返回
		 */
		formatDatelineToAgoStr : function(dateline) {
			if(!Number(dateline)) {
				return dateline;
			}
			if(!dateline) {
				return '';
			}
			var minute = 60;
	    	var hour = 3600;
	    	var day = 86400;
	    	var moon = 2592000;
	    	var year = 31104000;
			var date = new Date();
			var curDateline = Math.round(Number(date.getTime())/1000);
			var time = curDateline - dateline;
	        var time = parseFloat(time);
	        if (null != time && "" != time) {
	        	if (time <=30) {
	        		time = "刚刚";
	        	} else if (time > 30 && time < 60) {
	            	time = parseInt(time) + "秒前";
	            } else if (time > minute && time < hour) {
	                time = parseInt(time / minute) + "分钟前";
	            } else if (time >= hour && time < day) {
	                time = parseInt(time / hour) + "小时前";
	            } else if (time >= day  && time < moon) {
	                time = parseInt(time / day) + "天前";
	            } else if (time >= moon  && time < year) {
	                time = formatDatelineToStr(dateline);
	            } else if (time >= year) {
	                time = formatDatelineToStr(dateline);
	            }  
	        }
			return time;
		},
        getOS: function(){
            var ua = window.navigator.userAgent,
                platform = window.navigator.platform,
                isWin = (platform == 'Win32') || (platform == 'Windows'),
                isXP;

            if(isWin){
                isXP = ua.indexOf('Windows NT 5.1') > -1 || ua.indexOf('Windows XP') > -1;
            }
            return {
                'isXP': isXP
            };
            
        },
        checkOS: function(){
            var os = Utils.getOS();

            if(os.isXP){
                jQuery('body').addClass('os-xp');
            }
        },
        /**
         * 处理某段文本，保证只显示指定长度的文本
         * @param text
         * @param num 显示长度，如果没有指定默认为16字
         * @param prefix 显示在结尾的占位符默认'...'
         */
        getLineText: function(text, num, prefix) {
            if(!text) return text;
            var len = 16;
            if (num) {
                len = num;
            }
            var index = 0;
            if (getLength(text) > len) {
                for (var i = 1;i <= text.length; i++) {
                    if (getLength(text.substr(0, i)) > len) {
                        index = i - 1;
                        break;
                    }
                }
            }
            if (index != 0) {
                text = text.substring(0, index) + (prefix || '...'); 
            }
            return text;
        },		
        //对get参数进行编码
        appEncodeURL: function(s) {
            var reg = /^[\u0391-\uFFE5%]+$/;
            var urlLength = s.length;
            var newS = "";
            for(var i = 0; i < urlLength; i++) {
                if(reg.test(s.charAt(i))) {
                    newS += escape(s.charAt(i));
                }
                else {
                    newS += s.charAt(i);
                }
            }
            if(newS.indexOf('_app_encoding_tag_=')== -1){
                if(newS.indexOf('?') >= 0) {
                    newS = newS + '&_app_encoding_tag_=1';
                }else{
                    newS = newS + '?_app_encoding_tag_=1';
                }
            }
            return encodeURI(newS);
        },
        phfix: function(selector){
        	// IE10开始 已支持placeholder
        	var isSupportPlaceHolder = 'placeholder' in document.createElement('input');
        	if (isSupportPlaceHolder) {
        	    return;
        	}
            var selector = selector || '.js-phfix';
            //placeholder fix for IE
            $(selector).placeholder();
        },        
        /**
         * jquery attr方法在ie10兼容模式下有bug
         */
        attr: function(ele, attrName, attrValue) {
            if(!ele) {
                return;
            }
            try{
                ele.setAttributeNode(attrName, attrValue);
            }catch(e) {
                ele.setAttribute(attrName, attrValue);
            }
        },
        /**
         * 获取str长度 一个汉字算2
         * TODO: IE下貌似不准确, 推荐Util.countStr(str)
         */
        getStringLen: function(str){
            if(!str){
                return ;
            }

            var length = 0;
            for (var i = str.length - 1; i >= 0; i--) {
                var s = str[i];
                if(s && s.match(/[^\x00-\xff]/g)!=null){
                    length+=2;
                }else{
                    length+=1;
                }
            }
            return length;
        },
        countStr: function(str){
            return getLength(str || '');
        },
        /**
         * 在可编辑的dom元素中插入内容，定位光标到文字后面
         * @param {DOM} obj 可编辑元素
         * @param {String} str 插入的内容
         */
        setEditablePointer: function(obj, str){
            var selection= window.getSelection ? window.getSelection() : document.selection;
            var range= selection.createRange ? selection.createRange() : selection.getRangeAt(0);
            if (!window.getSelection){
                obj.focus();
                var selection= window.getSelection ? window.getSelection() : document.selection;
                var range= selection.createRange ? selection.createRange() : selection.getRangeAt(0);
                range.pasteHTML(str);
                range.collapse(false);
                range.select();
            }else{
                obj.focus();
                range.collapse(false);
                var hasR = range.createContextualFragment(str);
                var hasR_lastChild = hasR.lastChild;
                while (hasR_lastChild && hasR_lastChild.nodeName.toLowerCase() == "br" && hasR_lastChild.previousSibling && hasR_lastChild.previousSibling.nodeName.toLowerCase() == "br") {
                    var e = hasR_lastChild;
                    hasR_lastChild = hasR_lastChild.previousSibling;
                    hasR.removeChild(e);
                }                                
                range.insertNode(hasR);
                if (hasR_lastChild) {
                    range.setEndAfter(hasR_lastChild);
                    range.setStartAfter(hasR_lastChild);
                }
                selection.removeAllRanges();
                selection.addRange(range);
            }
        },
        //生成32位唯一id
        uuid: function() {
            return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0,
                    v = c == "x" ? r : (r & 3 | 8);
                return v.toString(16);
            }).toUpperCase();
        },
        
        isHasEmoji : function(str) {
        	var len = str.length;
            for (var i = 0; i < len; i++) {
                var codePoint = str.charCodeAt(i);
                if (isEmojiCharacter(codePoint)) {
                    return true;
                }
            }
            return false;
        },
        
        juicerIndexAdd : function(index) {
        	return Number(index)+1;
        }
        
	};
}();